package com.longtop.framework.sys.role.web;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.longtop.framework.base.BaseAction;
import com.longtop.framework.common.CacheUtil;
import com.longtop.framework.common.Constant;
import com.longtop.framework.common.QueryConditions;
import com.longtop.framework.common.QueryResult;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.sys.auth.model.TSysAuthData;
import com.longtop.framework.sys.auth.model.TSysAuthOper;
import com.longtop.framework.sys.auth.service.AuthDataService;
import com.longtop.framework.sys.auth.service.AuthOperService;
import com.longtop.framework.sys.func.model.TSysFunc;
import com.longtop.framework.sys.func.service.FuncService;
import com.longtop.framework.sys.menu.model.TSysMenu;
import com.longtop.framework.sys.menu.service.MenuService;
import com.longtop.framework.sys.role.model.TSysRole;
import com.longtop.framework.sys.role.service.RoleService;
import com.longtop.framework.util.BeanUtil;
import com.longtop.framework.util.StringUtil;
import com.longtop.framework.util.WebUtil;
import com.longtop.intelliweb.action.IActionContext;
import com.longtop.intelliweb.action.IInitContext;
import com.longtop.intelliweb.view.Dataset;
import com.longtop.intelliweb.view.ListDropDown;
import com.longtop.intelliweb.view.ListDropDownItem;
import com.longtop.intelliweb.view.Panel;
import com.longtop.intelliweb.view.Parameter;

/**
 * 分配权限Action类
 * 
 * @author 胡砥峰
 * @version 1.0
 * 
 */
public class RoleAuthAction extends BaseAction {

	// 页面数据集
	private static final String DATASET_AUTHOPER = "Dataset_AuthOper";
	private static final String DATASET_AUTHDATA = "Dataset_AuthData";

	/**
	 * 初始化页面
	 * 
	 * @param context
	 */
	public void init(IInitContext context) {
		super.init(context);

		// 获取页面数据集
		Dataset authOperDataset = context.getDataset(DATASET_AUTHOPER);

		// 验证是否存在
		if (!WebUtil.validateDatasetExist(this, authOperDataset, DATASET_AUTHOPER)) {
			return;
		}

		// 得到角色id
		String roleId = context.getRequest().getParameter("roleId");

		// 调用spring的业务逻辑
		RoleService roleService = getBean(RoleService.BEAN_ID);
		FuncService funcService = getBean(FuncService.BEAN_ID);
		AuthOperService authOperService = getBean(AuthOperService.BEAN_ID);

		// 角色操作权限列表
		List authOperList = authOperService.getAuthOperListByRoleId(roleId);

		// 所有菜单list
		MenuService menuService = getBean(MenuService.BEAN_ID);
		List menuList = menuService.getMenuList();

		// 加载功能权限
		QueryConditions conditions = WebUtil.createQueryConditions();
		QueryResult queryResult = funcService.loadFunc(conditions);

		// 所有功能list
		List funclist = queryResult.getResultList();

		// 移动到dataset首记录
		authOperDataset.moveBeforeFirst();

		// 加载菜单
		Iterator it = menuList.iterator();
		while (it.hasNext()) {
			TSysMenu menu = (TSysMenu) it.next();

			// 新建record
			authOperDataset.newRecord();

			authOperDataset.setValue("menuOrFuncId", menu.getMenuId());
			authOperDataset.setValue("operName", menu.getMenuName());
			authOperDataset.setValue("authType", Constant.OPER_TYPE_01);
			authOperDataset.setValue("parentmenuOrFuncId", menu.getParentMenuId());
			authOperDataset.setValue("hasChecked", hasChecked(authOperList, menu.getMenuId(), Constant.OPER_TYPE_01));
		}

		int count = funclist.size();
		TSysFunc func;
		for (int i = 0; i < count; i++) {
			func = (TSysFunc) funclist.get(i);

			// 新建record
			authOperDataset.newRecord();

			authOperDataset.setValue("menuOrFuncId", func.getFuncId());
			authOperDataset.setValue("operName", func.getFuncName());
			authOperDataset.setValue("authType", Constant.OPER_TYPE_02);
			authOperDataset.setValue("parentmenuOrFuncId", func.getMenuId());
			authOperDataset.setValue("hasChecked", hasChecked(authOperList, func.getFuncId(), Constant.OPER_TYPE_02));
		}

		// 动态改变界面上显示的信息
		TSysRole tbXtRole = (TSysRole) roleService.get(TSysRole.class, roleId);
		String roleName = tbXtRole != null ? tbXtRole.getRoleId() : "";
		if (roleName == null) {
			roleName = "";
		}

		// 设置panel标题
		Panel panel1 = (Panel) context.getControl("Panel1");
		if (panel1 != null) {
			String captionStr = new StringBuffer().append("功能权限选择: ").append(roleName).toString();
			panel1.setCaption(captionStr);
			panel1.setTag(roleId);
		}

		// ****************开始处理数据权限***************
		Panel panel2 = (Panel) context.getControl("Panel2");
		if (panel2 != null) {
			String captionStr = new StringBuffer().append("数据权限列表: ").append(roleName).toString();
			panel2.setCaption(captionStr);
			panel2.setTag(roleId);
		}

		// 加载ListDropDown，业务对象
		ListDropDown listDropDown_TableName = (ListDropDown) context.getControl("ListDropDown_TableName");
		if (listDropDown_TableName != null) {
			// 加载各项数据
			List tableNameList = CacheUtil.getCodeInfoListByCodeTypeId(Constant.CODE_TYPE_0001);

			// 加入空白记录
			ListDropDownItem listDropDownItem = new ListDropDownItem();
			listDropDownItem.setName("");
			listDropDownItem.setValue(Constant.DATA_AUTH_ALL_TABLE_NAME);
			listDropDownItem.setLabel("所有业务对象");
			listDropDown_TableName.addItem(listDropDownItem);

			// this.fillCodeInfoToListDropDown(tableNameList, listDropDown_TableName);
		}

		// 加载数据权限
		Dataset datasetAuthData = context.getDataset(DATASET_AUTHDATA);

		// 验证是否存在
		if (!WebUtil.validateDatasetExist(this, datasetAuthData, DATASET_AUTHDATA)) {
			return;
		}

		// 调用spring业务逻辑
		AuthDataService authDataService = getBean(AuthDataService.BEAN_ID);

		List list = authDataService.getAuthDataListByRoleId(roleId);
		if (list != null && list.size() > 0) {
			try {
				BeanUtil.listToDataset(list, datasetAuthData);
			} catch (Exception e) {
				e.printStackTrace();
				hintErrorMessage(e.getMessage());
			}
		}
	}

	/**
	 * 提交保存数据_功能权限
	 * 
	 * @param context
	 *            intelliWeb Web
	 */
	public void saveRoleAuthOper(IActionContext context) {

		// 获取页面数据集
		Dataset authOperDataset = context.getDataset(DATASET_AUTHOPER);
		if (!WebUtil.validateDatasetChange(this, authOperDataset, DATASET_AUTHOPER)) {
			return;
		}

		// 得到页面命令参数
		Parameter parameter = context.getCommandParameter("roleId");
		String roleId = "";
		if (parameter != null) {
			roleId = parameter.getValue();
		}

		// 调用spring的业务逻辑
		AuthOperService authOperService = getBean(AuthOperService.BEAN_ID);

		// SessionObject对象
		SessionObject sessionObject = this.getSessionObject(context);

		try {
			List list = BeanUtil.datasetSelectedToList(authOperDataset, TSysAuthOper.class, "parentOperId,operName,hasChecked", "hasChecked", "1");

			Integer[] count = authOperService.saveAuthOper(list, roleId, sessionObject);

		} catch (Exception e) {
			log.logError(e.getMessage(), e);
			this.hintErrorMessage(e.getMessage());
		}
	}

	/**
	 * 验证是否有权限
	 * 
	 * @param TSysAuthOperList
	 *            角色功能列表
	 * @param operId
	 *            角色功能Id
	 * @param operType
	 *            权限类型
	 * @return "1" 有权限；"0"没权限
	 */
	private String hasChecked(List TSysAuthOperList, String operId, String operType) {
		Iterator it = TSysAuthOperList.iterator();
		TSysAuthOper bean;
		while (it.hasNext()) {
			bean = (TSysAuthOper) it.next();
			if (bean.getMenuOrFuncId().equals(operId) && bean.getAuthType().equals(operType)) {
				return "1";
			}
		}

		return "0";
	}

	/**
	 * 保存数据权限
	 * 
	 * @param context
	 */
	public void saveRoleAuthData(IActionContext context) {
		// 得到页面数据集
		Dataset authDataDataset = context.getDataset(DATASET_AUTHDATA);
		if (!WebUtil.validateDatasetChange(this, authDataDataset, DATASET_AUTHDATA)) {
			return;
		}

		// spring业务逻辑
		AuthDataService authDataService = getBean(AuthDataService.BEAN_ID);

		// SessionObject对象
		SessionObject sessionObject = this.getSessionObject(context);

		try {
			Map changeMap = WebUtil.datasetToObjectList(authDataDataset, "id", TSysAuthData.class);
			authDataService.saveAuthData(changeMap, sessionObject);

			// 刷新页面数据
			loadAuthData(context, authDataDataset);

		} catch (BaseCheckedException e) {
			this.hintErrorMessage(e.getMessage());
			return; // 返回
		} catch (Exception e) {
			// 记入日志
			log.logError(e.getMessage());
			// 在界面显示错误信息
			this.hintErrorMessage(e.getMessage());
		}
	}

	/**
	 * 数据权限保存成功后，刷新页面数据
	 * 
	 * @param context
	 * @param datasetAuthData
	 */
	private void loadAuthData(IActionContext context, Dataset datasetAuthData) {
		if (datasetAuthData != null && datasetAuthData.size() > 0) {
			if (!StringUtil.isStrEmpty(datasetAuthData.getString("roleId"))) {
				String roleId = datasetAuthData.getString("roleId");

				// 调用spring业务逻辑
				AuthDataService authDataService = getBean(AuthDataService.BEAN_ID);

				List list = authDataService.getAuthDataListByRoleId(roleId);
				if (list != null && list.size() > 0) {
					try {
						BeanUtil.listToDataset(list, datasetAuthData, false);
					} catch (Exception e) {
						e.printStackTrace();
						hintErrorMessage(e.getMessage());
					}
				}
			}
		}
	}
}